//
//  WLRoutersVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/15.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRoutersVController.h"
#import "WLRoutersCell.h"
//#import "WLScanBindingRouterController.h"
#import "WLRouterBingFlowController.h"

@interface WLRoutersVController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tbRouter;
@property (nonatomic, strong) NSMutableArray *arrRouters;
@property (nonatomic, assign) NSInteger pagesRouter;
@property (nonatomic, assign) BOOL needChangeDevice;


@end

@implementation WLRoutersVController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的设备";
    
    UIButton *btnMyCard = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    [btnMyCard setImage:[UIImage imageNamed:@"router_add"] forState:UIControlStateNormal];
    [btnMyCard addTarget:self action:@selector(addRouterAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithCustomView:btnMyCard];
    self.navigationItem.rightBarButtonItem = rightBar;
    
    WLWkSelf
    _arrRouters = [[NSMutableArray alloc] init];
    _pagesRouter = 1;
    _tbRouter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbRouter.delegate = self;
    _tbRouter.dataSource = self;
    _tbRouter.rowHeight = WLScaleX(64);
    _tbRouter.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)) {
        _tbRouter.estimatedSectionHeaderHeight = 0;
    }
    [self.view addSubview:_tbRouter];
    [_tbRouter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    _tbRouter.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        [weakSelf refresh];
    }];
    
    [self reqMyRouters];
}

- (void)refresh {
    
    self.tbRouter.mj_footer = nil;
    //        [weakSelf.arrRouters removeAllObjects];
    self.pagesRouter = 1;
    [self reqMyRouters];
}
- (void)addRouterAction
{
    WLRouterBingFlowController *bindRouterController = [[WLRouterBingFlowController alloc] init];
    [self.navigationController pushViewController:bindRouterController animated:YES];
//    WLScanBindingRouterController *scanController = [[WLScanBindingRouterController alloc] init];
//    [self.navigationController pushViewController:scanController animated:YES];
}

- (void)addFooterRefresh
{
    WLWkSelf
    _tbRouter.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqMyRouters];
    }];
}

//{
//    active = 0;
//    addTime = 1538275710000;
//    current = 0;
//    desc = "<null>";
//    deviceId = 8972400906;
//    deviceName = "小鸟路由器";
//    enable = 1;
//    hasBind = 1;
//    id = 106;
//    macAddress = "08:00:20:0A:8C:2D";
//    online = 0;
//    path = "<null>";
//    rank = 0;
//    remark = "<null>";
//    userid = 41;
//}
- (void)reqMyRouters
{
    WLWkSelf
    NSDictionary *conditions = @{};
    NSDictionary *pages = @{@"page":[NSNumber numberWithInteger:_pagesRouter],@"num":@10};
    NSDictionary *paramsp = @{@"conditions":conditions,@"page":pages};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/app/list/user" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tbRouter.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"count"] integerValue];
        if (strongSelf.pagesRouter==1)
        {
            [strongSelf.arrRouters removeAllObjects];
            if (productCount>10)
            {
                [strongSelf addFooterRefresh];
            }
        }
        NSArray *arrPros = successDict[@"object"];
        if ([arrPros isKindOfClass:[NSArray class]] && arrPros.count>0) {
            [strongSelf.arrRouters addObjectsFromArray:arrPros];
            if (strongSelf.arrRouters.count >= productCount) {
                [strongSelf.tbRouter.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tbRouter.mj_footer endRefreshing];
            }
//            [strongSelf.tbRouter reloadData];
        }
        else
        {
            [strongSelf.tbRouter.mj_footer endRefreshingWithNoMoreData];
        }
        [strongSelf.tbRouter reloadData];
        [strongSelf checkNeedChangeDevice];
        strongSelf.pagesRouter += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.tbRouter.mj_header endRefreshing];
        [weakSelf.tbRouter.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.tbRouter.mj_header endRefreshing];
        [weakSelf.tbRouter.mj_footer endRefreshing];
    } inView:(_pagesRouter==1&&[self.tbRouter.mj_header isRefreshing]==NO)?self.view:nil];
}
- (void)checkNeedChangeDevice {
    if (self.needChangeDevice) {
        self.needChangeDevice = NO;
        NSInteger index = -1;
        for (NSInteger i=0; i<self.arrRouters.count; i++) {
            NSDictionary *dictR = self.arrRouters[i];
            if ([dictR[@"current"] integerValue]==1)
            {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            [self deletedRouterUpdateTable:index];
        }
    }
}
#pragma mark - UITableView
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSDictionary *model = self.arrRouters[indexPath.row];
//    if ([model[@"current"] integerValue] == 1)
//    {
//        return NO;
//    }
    return YES;
}

-  (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSDictionary *model = self.arrRouters[indexPath.row];
//    if ([model[@"current"] integerValue]==1) {
//        return UITableViewCellEditingStyleNone;
//    }
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"移除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    WLWkSelf
    NSDictionary *model = self.arrRouters[indexPath.row];
    NSDictionary *paramsp = @{@"deviceId":model[@"deviceId"]};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/untied" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        [weakSelf.arrRouters removeObjectAtIndex:indexPath.row];
        [weakSelf.tbRouter deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        if (weakSelf.arrRouters.count > 0) {
            [weakSelf judgeNeedUpdateWithModel:model];
        } else {//没有设备了
            [[WLSocketManager sharedSocketManager] userManualdisconnect];
            [WLUseManager shareUser].routerModel = nil;
            [weakSelf goToDeviceBingding];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {

    } inView:self.view];
}
- (void)goToDeviceBingding
{
    WLRouterBingFlowController *flowController = [[WLRouterBingFlowController alloc] init];
    flowController.isPresented = NO;
    flowController.isPopDisabled = YES;
    flowController.isPopToMain = YES;
    [self.navigationController pushViewController:flowController animated:YES];
}
- (void)judgeNeedUpdateWithModel:(NSDictionary *)model {
    if ([model[@"current"] integerValue] == 1) {
        self.needChangeDevice = YES;
        [_tbRouter.mj_header setState:MJRefreshStateRefreshing];
        [self refresh];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return WLScaleX(20);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrRouters.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strRouters = @"routersCell";
    WLRoutersCell *cell = [tableView dequeueReusableCellWithIdentifier:strRouters];
    if (!cell) {
        cell = [[WLRoutersCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strRouters];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSDictionary *dictRouter = self.arrRouters[indexPath.row];
    if ([dictRouter[@"current"] integerValue]==1) {
        cell.btnChange.hidden = YES;
        cell.labCurDevice.hidden = NO;
    }
    else
    {
        cell.labCurDevice.hidden = YES;
        cell.btnChange.hidden = NO;
        cell.btnChange.tag = indexPath.row;
        [cell.btnChange addTarget:self action:@selector(changeRouterAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    if ([dictRouter[@"online"] integerValue]==1) {
        cell.ivHead.image = [UIImage imageNamed:@"router_blue"];
        cell.labStatus.text = @"在线";
        cell.labStatus.textColor = wlGreenColor;
    }
    else
    {
        cell.ivHead.image = [UIImage imageNamed:@"router_gray"];
        cell.labStatus.text = @"离线";
        cell.labStatus.textColor = wlLightTextColor;
    }
    if ([dictRouter[@"deviceName"] isKindOfClass:[NSNull class]]==NO) {
        cell.labTitle.text = dictRouter[@"deviceName"];
    }
    else
    {
        cell.labTitle.text = @"";
    }
    if ([dictRouter[@"deviceId"] isKindOfClass:[NSNull class]]==NO) {
        cell.labRouterID.text = [NSString stringWithFormat:@"ID：%@",dictRouter[@"deviceId"]];
    }
    else
    {
        cell.labRouterID.text = @"";
    }
    
    return cell;
}

- (void)changeRouterAction:(UIButton *)btnChange
{
    NSInteger index = btnChange.tag;
    NSDictionary *dictRouter = self.arrRouters[index];
    WLWkSelf
    NSDictionary *paramsp = @{@"deviceId":dictRouter[@"deviceId"]};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/set/current" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        [weakSelf changedRouterUpdateTable:index];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)changedRouterUpdateTable:(NSInteger)index
{
    
    for (NSInteger i=0; i<self.arrRouters.count; i++) {
        NSDictionary *dictR = self.arrRouters[i];
        if ([dictR[@"current"] integerValue]==1)
        {
            NSMutableDictionary *dictL = [NSMutableDictionary dictionaryWithDictionary:dictR];
            [dictL setObject:@0 forKey:@"current"];
            [self.arrRouters replaceObjectAtIndex:i withObject:dictL];
            break;
        }
    }
    
    NSDictionary *dictMN = self.arrRouters[index];
    NSMutableDictionary *dictN = [NSMutableDictionary dictionaryWithDictionary:dictMN];
    [dictN setObject:@1 forKey:@"current"];
    [self.arrRouters replaceObjectAtIndex:index withObject:dictN];
    [self.tbRouter reloadData];
    
    //断开socket连接，请求user信息后再连接
    [[WLSocketManager sharedSocketManager] userManualdisconnect];
    [self queryUserInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNOTIFICATION_CHANGED object:nil];
}
- (void)deletedRouterUpdateTable:(NSInteger)index
{
    //断开socket连接，请求user信息后再连接
    [[WLSocketManager sharedSocketManager] userManualdisconnect];
    [self queryUserInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNOTIFICATION_CHANGED object:nil];
}
- (void)queryUserInfo
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/query" withParamsDic:nil success:^(NSDictionary *successDict) {
//        __strong typeof(self) strongSelf = weakSelf;
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
        [[WLUseManager shareUser] requestRouterInfo];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
